package service;

import com.alibaba.fastjson.parser.deserializer.SqlDateDeserializer;
import dao.BookDao;
import domin.Book;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;

public class Bookservice {
    private BookDao bookDao = BookDao.getInstance();
    private static Bookservice bookservice = new Bookservice();
    public static Bookservice getInstance(){
        return  bookservice;
    }

    public Collection<Book> findAll(Collection<Condition> condition, Pagination pagination) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Book> books = bookDao.findAll(connection,condition,pagination);
        JdbcHelper.close(connection);
        return books;
    }

    public Book find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Book book = bookDao.find(connection,id);
        JdbcHelper.close(connection);
        return book;
    }
    public Collection<Book> getAllWithCondition(String s) throws SQLException{
        Collection<Book>  collection = new HashSet<Book>();
        Connection connection = JdbcHelper.getConn();
            Collection<Book> books = BookDao.getInstance().getAllWithCondition(connection,s);
            collection.addAll(books);
        JdbcHelper.close(connection);
        return collection;
    }

    public boolean update(Book book) throws SQLException {
        boolean updated = false;
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
            updated = bookDao.update(connection,book);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return updated;
    }

    public boolean add(Book book) throws SQLException {
        boolean added =false;
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
            added = bookDao.add(connection, book);
            connection.commit();
        }
        catch (SQLException e){
            connection.rollback();
        }
        finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return added;
    }

    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        boolean deleted =bookDao.delete(connection,id);
        JdbcHelper.close(connection);
        return deleted;
    }
}
